﻿using System.Collections.Generic;
using com.guojin.core.io.message;
using com.guojin.mj.net.message.game;
using com.guojin.mj.net.message.login;
using UnityEngine;

public class GameRoomController : MonoBehaviour
{
    private static GameRoomController instance;

    public static GameRoomController GetInstance()
    {
        if (instance == null)
            instance = new GameRoomController();
        return instance;
    }

    private GameRoomInfoRet gri;

    #region//加载房间信息
    public void OnReceiveMsg127(string msg, Message data)
    {
        gri = (GameRoomInfoRet) data;

        DelePageBeforeLoadGameRoomPage();

        UIManager.ChangeUI(UIManager.PageState.GameRoomPage,
            obj =>
            {
                obj.GetComponent<GameRoomPage>().InformationSetting();
                InitRoomInfo();
            });
    }

    private void DelePageBeforeLoadGameRoomPage()
    {
        if (GameObject.Find("GameRoomPage(Clone)"))
            GameObject.Find("GameRoomPage(Clone)").GetComponent<GameRoomPage>().CloseBtnClick();

        if (GameObject.Find("CreatRoomPage(Clone)"))
            GameObject.Find("CreatRoomPage(Clone)").GetComponent<CreateRoomPage>().CloseBtnClick();

        if (GameObject.Find("TrusteeShipPage(Clone)"))
            GameObject.Find("TrusteeShipPage(Clone)").GetComponent<TruesteeShipPage>().CloseBtnClick();
    }

    private void InitRoomInfo()
    {
        if (gri != null)
            StartInitRoomInfo(gri);
        else
            Debug.Log("GameRoomController中保存的GameRoomInfoRet消息为null");
    }

    private void StartInitRoomInfo(GameRoomInfoRet GTI)
    {
        Debug.Log("当前房间状态："+GTI.chapter.state);

        GameController.GetInstance().SaveOptionsToOptionDic(GTI.options);         //保存规则

        GameRoomModel.GetInstance().SaveRoomInfoToGameRoomModel(GTI);  //保存房间信息

        GetPlayerUserIDAndLocationIndexFromGameUser(GTI.gameUser);             //获取当前玩家locationIndex和userId  判断是不是房主

        GameController.GetInstance().InitPlayerPosition();                                         //根据玩家location生成位置数组

        GameRoomModel.GetInstance().GameStartAppendPlayersToPlayerDic(GTI.gameUser);    //生成头像 , 名字 分数（设置引用）

        if ((GTI.state == 0) && (GameData.GetInstance().roomHostUserID == GameData.GetInstance().userID))
        {
            //如果是房主，显示邀请和开始按钮
            SetBtnStateBeforeGameStart();
        }

        InitChapterInfo(GTI.chapter);                                                     //设置房间状态 和  显示庄

        InitAllPlayerUserChapterInfo(GTI.chapter.userChapterInfo);     //生成玩家手牌,  玩家总分, 下注分, 出牌已完成, 结算分 

        // 0游戏未开始 1抢庄状态 2下注状态 3出牌状态 4结算
        if (GTI.chapter.state == 1 )
        {
            ShowVieZhuangBtn();
        }
        else if (GTI.chapter.state == 2)
        {
            SetBetState(GTI);
        }
        else if (GTI.chapter.state == 3)
        {
            SetDealCardState(GTI);
        }
        else if (GTI.chapter.state == 4)
        {
            SetChapterEndState(GTI.chapter.userChapterInfo);
        }
    }

    private void GetPlayerUserIDAndLocationIndexFromGameUser(List<GameUserInfoRet> gameUser)
    {
        for (var i = 0; i < gameUser.Count; i++)
            if (gameUser[i].userId.ToString() == GameData.GetInstance().userID)
            {
                GameData.GetInstance().locationIndex = gameUser[i].locationIndex;
                GameData.GetInstance().userID = gameUser[i].userId.ToString();
            }
    }

    private void SetBtnStateBeforeGameStart()
    {
        ShowStartBtnState();
        ShowInviteBtnState();
    }

    private void InitChapterInfo(ChapterInfoRet chapter)
    {
        GameRoomModel.GetInstance().existRoom = true;

        GameRoomModel.GetInstance().RoomState = chapter.state;

        if (chapter.zhuangLocationIndex >= 0 && chapter.state != 0)
        {
            Debug.Log(chapter.zhuangLocationIndex);
            Debug.Log(chapter.state);
            GameRoomModel.GetInstance().zhuangIndex = chapter.zhuangLocationIndex;
            ShowZhuang(chapter.zhuangLocationIndex);
        }
    }
       
    private void InitAllPlayerUserChapterInfo(List<UserChapterInfoRet> userChapterInfo)
    {
        if (userChapterInfo != null)
        {
            for (var i = 0; i < userChapterInfo.Count; i++)                                       //手牌自动生成， 牌型自动显示，玩家状态,  分数自动显示； 
            {
                if (userChapterInfo[i].LocationIndex != -1 && !GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].isMiddleJoin)
                {
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].InitPlayerChapterInfo(userChapterInfo[i]);
                }
            }
        }
    }

    private void ShowZhuang(int locationIndex)
    {
        GameRoomModel.GetInstance().playerDic[locationIndex].ShowZhuang(true);
    }

    private void SetBetState(GameRoomInfoRet GTI)
    {
        if (GameData.GetInstance().locationIndex > 0)
        {
            if ((GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].BetScore == 0))     //当前玩家没有下注并且不是庄
                CheckAutoBetOrPlayerBet();
        }                         
    }

    private void SetDealCardState(GameRoomInfoRet GTI)
    {
            //如果自己已经坐下 且 不是中途加入。
            if ((GameData.GetInstance().locationIndex > -1)&&(GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].isMiddleJoin == false))
            {
                    //如果没有出牌 显示没牛按钮 , 如果自己出过拍了出过牌了， 显示 牌型，牌上打钩
                    if (GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].DealState == 0)
                    {
                        CheckAutoNiuOrPlayerDeal();
                    } 
                    else
                    {
                        GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].ShowCardPitchBaseCardType(GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].cardType);
                        GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].ShowCardType(true,"");
                    }
            }        
    }

    public void SetChapterEndState(List<UserChapterInfoRet> userChapterInfo)
    {
        if (userChapterInfo != null)
        {
            for (int i = 0; i < userChapterInfo.Count; i++)
            {
                if (userChapterInfo[i].LocationIndex != -1 && !GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].isMiddleJoin)
                {
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowCardBaseCardType(userChapterInfo[i].Cards);
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowCardPitchBaseCardType(GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].cardType);
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowSettleScore(true, userChapterInfo[i].SettlementScore);
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowCardType(true, "");
                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowReady(true);
//                    GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].ShowCardDistance(
//GameRoomModel.GetInstance().playerDic[userChapterInfo[i].LocationIndex].cardType);
                }
            }
        } 
    }
    #endregion


    //显示按钮
    public void ShowStartBtnState()
    {
        GameRoomPage.GetInstance().SetStartBtn(1);
    }

    public void ShowVieZhuangBtn()
    {
        if (GameData.GetInstance().locationIndex != -1)
        {
            if (GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore  <  GameRoomModel.GetInstance(). MinTakeInScore*0.3)
            {
                GameRoomPage.GetInstance().SetVieZhuangBtn(2);
            }
            else
            {
                GameRoomPage.GetInstance().SetVieZhuangBtn(1);
            }
        }      
    }

    public void ShowInviteBtnState()
    {
        GameRoomPage.GetInstance().SetInviteBtn(1);
    }

    public void ShowNoNiuBtn()
    {
        GameRoomPage.GetInstance().SetNoNiuBtn(1);
    }

    public void CheckAutoNiuOrPlayerDeal()
    {
        if (GameData.GetInstance().locationIndex != -1 && GameRoomModel.GetInstance().RoomState == 3 && GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].DealState == 0)
        {
            if (!GameRoomModel.GetInstance().AutoNiu)
            {
                 ShowNoNiuBtn();

                if (!GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].isMiddleJoin)
                {
                    GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].ShowCardValue();
                }
            }
            else
            {
                MessageManager.GetInstance()
                    .SendMsg1210(GameData.GetInstance().locationIndex,2, InitCardArrBaseCardList());
            }
        }
    }

    private int[] InitCardArrBaseCardList()
    {
        int[] cards = new int[5];
        for (int i = 0; i < 5; i++)
        {
            cards[i] = GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].handCardsList[i];
        }
        return cards;
    }


    public void CheckAutoBetOrPlayerBet()
    {
        if (GameData.GetInstance().locationIndex != -1 && GameData.GetInstance().locationIndex != GameRoomModel.GetInstance().zhuangIndex && GameRoomModel.GetInstance().RoomState == 2 && GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].isMiddleJoin == false)
        {
            if (!GameRoomModel.GetInstance().AutoBet)
            {
                UIManager.ChangeUI(UIManager.PageState.BetPage, (GameObject obj) =>
                {
                    obj.GetComponent<BetPage>().InformationSetting();
                    obj.transform.SetSiblingIndex(0);
                });
            }
            else
            {
                if (GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore > GameRoomModel.GetInstance().BotScore*5)
                {
                    MessageManager.GetInstance()
                        .SendMsg1212(1, GameData.GetInstance().locationIndex, GameRoomModel.GetInstance().BotScore);
                }
                else if(GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore < GameRoomModel.GetInstance().BotScore * 5 && GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore > GameRoomModel.GetInstance().BotScore )
                {
                    MessageManager.GetInstance()
                     .SendMsg1212(2, GameData.GetInstance().locationIndex, GameRoomModel.GetInstance().BotScore);
                }
                else if (GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore < GameRoomModel.GetInstance().BotScore)
                {
                    MessageManager.GetInstance()
                     .SendMsg1212(2, GameData.GetInstance().locationIndex, GameRoomModel.GetInstance().playerDic[GameData.GetInstance().locationIndex].TotalScore);
                }
            }
        }     
    }


    //开始游戏，12.3发牌时调用
    public void StartGame()
    {    
        //房间状态， 设置局数
            if (GameRoomModel.GetInstance().VieForZhuang == false)
            {
                GameRoomModel.GetInstance().RoomState = 2;
                DownTime.GetInstance().StartDownTime(10);
                CheckAutoBetOrPlayerBet();
            }
            else
            {
                GameRoomModel.GetInstance().RoomState = 1;
                DownTime.GetInstance().StartDownTime(3);
                GameRoomController.GetInstance().ShowVieZhuangBtn();
            }

        GameRoomModel.GetInstance().CurrentChapter += 1;
    }

    //点击准备 按钮调用
    public void GameStartInitPlayerInfo(DealCardsRet gd)
    {

        GameData.GetInstance().isClickThisChapter = false;

        //初始化玩家牌局信息
        foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
        {
            Debug.Log("玩家" + item.locationIndex + " 信息初始化");
            item.GameReadyInitUser();

            item.isMiddleJoin = true;

            for (int i = 0; i < gd.cardMsg.Count; i++)
            {
                if (item.locationIndex == gd.cardMsg[i].LocationIndex)
                {
                    item.isMiddleJoin = false;
                }         
            }

            //if (item.TotalScore > 0)
            //{
            //    item.isMiddleJoin = false;
            //}
            //else
            //{
            //    item.isMiddleJoin = true;
            //}
        }
    }

    #region //房间消息处理
    public void OnReceiveMsg73(string msg, Message data)
    {
        var dr = (DissolveRoomRet) data;

        if (dr.roomID != GameRoomModel.GetInstance().RoomID)
        {
            Debug.Log("解散消息不是当前房间" + dr.roomID);
            return;
        }
        else
        {
            GameRoomModel.GetInstance().existRoom = false;
        }

        if (GameObject.Find("VoteDissolveRoomPage(Clone)"))
            GameObject.Find("VoteDissolveRoomPage(Clone)").GetComponent<VoteDissolveRoomPage>().CloseBtnClick();

        if (GameRoomModel.GetInstance().RoomState == 0)
        {
            GameController.GetInstance().DeleteAllExceptGameHall();

            if (!GameObject.Find("GameHall(Clone)"))
            {
                UIManager.ChangeUI(UIManager.PageState.GameHallPage,
                    obj =>
                    {
                        obj.GetComponent<GameHallPanel>().InformationSetting();
                    });
            }
        }
        else if (GameRoomModel.GetInstance().RoomState != 0)
            if (GameObject.Find("GameRoomPage(Clone)"))
            {
                UIManager.ChangeUI(UIManager.PageState.GameEndPage,
                      obj =>
                      {
                          obj.GetComponent<GameEndPage>().InformationSetting();
                          obj.GetComponent<GameEndPage>().Init(dr);
                      });
            }
            else
                Debug.Log("没有找到GameRoomPage面板，RoomState != 0");
    }



    //退出房间
    public void OnReceiveMsg75(string msg, Message data)
    {
        var er = (ExitRoomRet) data;

        if (er.roomID != GameRoomModel.GetInstance().RoomID)
            Debug.Log("退出消息不是当前房间" + er.roomID);
        else
            ExitRoom(er.userID);
    }

    private void ExitRoom(int userID)
    {
        if (userID.ToString() != GameData.GetInstance().userID)
        {
            if (GameRoomModel.GetInstance().waitPlayerDic.ContainsKey(userID.ToString()))
            {
                  //退出不移除
            }
            else
            {
                foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
                {
                    if (item.userId == userID)
                    {
                        item.ExitRoomDeleteHead();
                    }
                }
            }
        }
        else
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
                GameController.GetInstance().DeleteAllExceptGameHall();

            if (!GameObject.Find("GameHall(Clone)"))
            {
                UIManager.ChangeUI(UIManager.PageState.GameHallPage,
                    obj =>
                    {
                        obj.GetComponent<GameHallPanel>().InformationSetting();
                    });
            }
        }
    }
    #endregion
}